<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>员工管理</title>
    <link rel="stylesheet" href="../../css/common.css">
    <link rel="stylesheet" href="../../layui/css/layui.css" media="all">
    <link id="layuicss-layer" rel="stylesheet" href="../../layui/css/modules/layer/default/layer.css" media="all">
    <script src="../../layui/layui.js"></script>
    <script src="..\..\js\jquery-3.4.1.min.js"></script>
</head>
<style>
    .selectFile{
        padding: 50px 20px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
<body>
    <div style="display: none;" id="saveDiv">
        <form class="layui-form" action="" lay-filter="dataFrm" id="dataFrm">
            <div class="layui-form-item">
                <label class="layui-form-label">员工名称</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="name" required="" lay-verify="required" placeholder="请输入员工名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">员工密码</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="password" required="" lay-verify="required" placeholder="请输入员工名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="email" required="" lay-verify="required" placeholder="请输入员工邮箱" autocomplete="off" class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="number" name="age" required="" lay-verify="required" placeholder="请输入员工年龄" autocomplete="off" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">部门</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="dept" required="" lay-verify="required" placeholder="请输入所属部门" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">日期</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="date" name="hireDate" required="" lay-verify="required" placeholder="请输入员工日期" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">日期</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="date" name="hireDate" required="" lay-verify="required" placeholder="请输入员工日期" autocomplete="off" class="layui-input">
                </div>
             </div>
            <div class="layui-form-item">
                <label class="layui-form-label">admin</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="number" name="admain" required="" lay-verify="required" placeholder="请输入员工admin" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="number" name="role" required="" lay-verify="required" placeholder="请输入员工角色" autocomplete="off" class="layui-input">
                </div>
            </div>
    
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="doSubmit1">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <div style="display: none;" id="UpdateDiv">
        <form class="layui-form" action="" lay-filter="dataFrom" id="dataFrom">
            <div class="layui-form-item">
                <label class="layui-form-label">id：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="number" name="id" required="" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="name" required="" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                </div>
            </div>
        
            <div class="layui-form-item">
                <label class="layui-form-label">密码：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="password" name="password" required="" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">验证密码：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="password" name="password" required="" lay-verify="required" placeholder="再输入一遍密码" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">Email：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="text" name="email" required="" lay-verify="required" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">年龄：</label>
                <div class="layui-input-block">
                    <input style="width: 250px" type="number" name="age" required="" lay-verify="required" placeholder="请输入年龄" autocomplete="off" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">超级管理员</label>
                <div class="layui-input-block">
                  <input type="radio" name="admin" value="1" title="是" checked=""><div class="layui-unselect layui-form-radio layui-form-radioed"><i class="layui-anim layui-icon"></i><div>是</div></div>
                  <input type="radio" name="admin" value="0" title="否"><div class="layui-unselect layui-form-radio"><i class="layui-anim layui-icon"></i><div>否</div></div>
                </div>
              </div>
    
            <div class="layui-form-item">
                <label class="layui-form-label">角色：</label>
                <div id="distribution" class="demo-transfer"></div>
            </div>
        
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="doSubmit2">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <div style="display: none;" id="selectFile">
        <form method="post" action="http://localhost:8888/sys/importExcel.do" enctype="multipart/form-data">
            <div class="selectFile">
                <input type="file" name="multipartFile" value="请选择文件">
                <input type="submit" value="提交">
            </div>
        </form>
    </div>
        <!-- 修改功能弹出层div结束 -->
    <div class="box">
        <div class="layui-card">
            <div class="layui-card-header"><h2>员工管理</h2></div>
            <div class="" style="margin: 10px 10px 10px 10px;">
                <fieldset class="fieldset" style="border: 1px solid darkgray;">
                    <legend style="font-size: large;">搜索信息</legend>
                    <div style="margin: 10px 10px 10px 10px">
                        <div class="layui-form layui-form-pane" >
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">关键字</label>
                                    <div class="layui-input-inline">
                                        <input id="keyword" type="text" name="keyword" id="demoReload" autocomplete="off" class="layui-input" placeholder="请输入姓名/邮箱">
                                        </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">部门</label>
                                    <div class="layui-input-block">
                                        <select name="type" id="typeSelect">
                                            <option value="" selected>请选择</option>
                                        </select>
                                    </div>
                                </div>

                                 <button type="submit" class="layui-btn" id="searchBtn" data-type="reload"><i class="layui-icon"></i> 搜 索</button>
                                <div class="layui-inline">
                                </div>
                            </div>
                        </div>
                    </div>
                </fieldset>
                </div>
                <!-- 表格数据 -->
            <div class="layui-card-body">
                <table class="layui-table" lay-data="{id: 'idTest'}" id="table" lay-filter="test"></table>
            </div>
            <div id="pageDemo" style="text-align: center"></div>
        </div>
    </div>
    <!-- 主界面结束 -->
    <!-- 头部工具栏 -->
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="getCheckData">批量删除</button>
            <button class="layui-btn layui-btn-sm" lay-event="importExcel">导入数据</button>
            <button class="layui-btn layui-btn-sm" lay-event="exportExcel">导出数据</button>
            <button class="layui-btn layui-btn-sm" lay-event="insert">新增</button>
        </div>
    </script>

    <!-- 行工具栏 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    <script>
        var department = []
        var roles = []
        $(document).ready(function(){
            //获取department列表
            $.get("http://localhost:8888/depart/list", function(res){
                department = res.data.data
                console.log("department", department)
            })

            $.get("http://localhost:8888/role/queryPage", function(res){
                roles = res.data.data
                console.log("roles", roles)
            })

        })

        layui.use(["table","form","laypage"],function(){
            var table = layui.table;
            var form = layui.form;
            var $ =layui.jquery;
            var laypage = layui.laypage;
            var transfer = layui.transfer;
            $.ajaxSetup({
                // 发送cookie
                xhrFields: {
                    withCredentials: true
                }
            });

            //前端接口（URL）接受后端数据进行数据表格的渲染
            var tableIns = table.render({
                elem:'#table',
                toolbar: '#toolbarDemo',
                url:'http://localhost:8888/sys/queryPage',
                parseData: function(res){ //res 即为原始返回的数据
                    getDepartment()         //渲染模糊查询部门下拉列表
                    return {
                        "code": 0, //解析接口状态
                        "msg": res.data.msg, //解析提示文本
                        "count": res.data.count, //解析数据长度
                        "data": res.data.data //解析数据列表
                    };
                },
                cols:[[
                    {field:'zizeng', title:'序号', width:80, type: 'numbers'},
                    {field:'select',type:"checkbox"},
                    {field:'id',title:'员工id',sort:true},
                    {field:'name',title:'员工姓名'},
                    {field:'email',title:'邮箱',sort:true},
                    {field:'age',title:'年龄'},
                    {field:'dept',title:'部门',templet:function(value){
                        return formatState1(value.dept)}},
                    {field:'admin',title:'用户类型',templet:function(value){
                        console.log("value.admin", value.admin)
                        return formatState(value.admin)
                    }},
                    {field:'操作',title:'操作',toolbar:'#barDemo',fixed:'right'}
                ]],
                page:{
                    layout:['prev','page','next','count']//,'limit','skip'
                    ,page:function(res){
                        return res.page
                    } //获取currentPage
                    // ,limit:function(res){
                    //     return res.limit
                    // }//获取pageSize
                    ,groups:10 //最多显示几个跳页按钮
                    ,first:true //显示首页
                    ,last:true  //显示尾页
                }
            });

            function getDepartment(){
                $.get("http://localhost:8888/depart/list", function(data){
                    var arr = data.data.data
                    department = data.data.data
                    // layui-anim layui-anim-upbit  <dd lay-value="11" class="">第一个选项</dd>
                    var typeSelect = document.getElementById("typeSelect")
                    arr.forEach(function (param) {
                        var option = document.createElement("option");
                        option.setAttribute("lay-value", param.id);
                        option.innerText = param.name;
                        typeSelect.appendChild(option)
                    })
                    form.render("select");
                });
            }
            
            function formatState(admin){
                var type;
                if(admin == 1){
                    type = "超级管理员"
                }else if(admin == 0){
                    type = "普通用户"
                }
                return type;
            }

            function formatState1(dept){
                var name;
                department.forEach(function (param) {
                    if(dept == param.id){
                        name = param.name
                    }
                })
                return name;
            }

            $(document).on('click','#searchBtn',function(data){
                alert("name:"+$("#keyword").val())
                tableIns.reload({
                    url:'http://localhost:8888/sys/queryPage',
                    where: { //设定异步数据接口的额外参数，任意设
                        keyword: $("#keyword").val(),
                        type: $("#type").val()
                    }
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                }); //只重载数据
            })
            //头部工具栏
            table.on('toolbar(test)',function (obj){
                //打印事件名
                console.log(obj);
                var checkStatus = table.checkStatus(obj.config.id);
                console.log(checkStatus);
                // 获取事件名
                var eventName = obj.event;
                switch (eventName){
                    case "getCheckData":
                        var arr = checkStatus.data;
                        var data = []
                        var url = "http://localhost:8888/sys/deleteByEmployeeIdList?"
                        arr.forEach(function(param){
                            url = url + "ids=" + param.id+"&"
                            data.push(param.id)
                        })
                        if(data.length >= 1){
                            $.post(url,function(res){
                                tableIns.reload();
                                layer.msg("删除了"+data.length+"条数据")
                            })
                        }else{
                            layer.msg("未选中任何数据！")
                        }
                        break;
                    case "importExcel":
                        mainIndex=layer.open({
                            type:1,
                            title:'选择文件',
                            content:$("#selectFile"),
                            area:['300px','200px'],
                            success:function (){
                                $("#dataFrm")[0].reset();
                                url="http://localhost:8888/sys/addEmployee";
                            },end:function(){
                                $("#selectFile").css("display",'none');
                            }
                        });
                    
                        break;
    
                    case "exportExcel":
                        var arr = checkStatus.data;
                        var data = []
                        var url = "http://localhost:8888/sys/exportExcel.do?"
                        arr.forEach(function(param){
                            url = url + "ids=" + param.id+"&"
                            data.push(param.id)
                        })
                        alert(url)
                        if(data.length >= 1){
                            layer.lo
                            window.location.href = url
                        }else{
                            layer.msg("未选中任何数据！")
                        }

                        // var flag = checkStatus.isAll;
                        // var str = flag ? '全选' : '未全选' ;
                        // layer.msg(str);
                        break;
                    //若点击“新增”按钮，进入该事件，调用新增方法openAdd();
                    case "insert":
                        openAdd();
    
                    default:
                        break;
                };
            });

                //行工具栏事件
                table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                    // console.log(obj);
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    // var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                    if(layEvent === 'del'){ //删除
                        layer.confirm('真的删除行么', function(index){
                            // obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            console.log(data);
                            console.log(data.id);
                            layer.close(index);
                            //向服务端发送删除指令
                            $.ajax({
                                url:'http://localhost:8888/sys/deleteByEmployeeId', //删除数据接口
                                type: 'POST',
                                data: {
                                id:data.id
                            },
                            success:function(res){
                            alert("删除成功");
                        //重新加载数据表格
                        tableIns.reload();
                        },
                            })
                            // obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                            //向服务端发送删除指令
                        });
                    } else if(layEvent === 'edit'){ //点击修改进入该事件，调用修改方法
                        openUpdate(data);
                        var obj = $("[name='id']").val();
                    }
            });
              
            var url;
            var mainIndex;
            //新增方法（函数）
            function  openAdd(data){
                mainIndex=layer.open({
                    type:1,
                    title:'新增',
                    content:$("#saveDiv"),
                    area:['800px','400px'],
                    success:function (){
                        $("#dataFrm")[0].reset();
                        url="http://localhost:8888/sys/addEmployee";
                    },end:function(){
                        $("#saveDiv").css("display",'none');
                    }
                });
            }
            
            //修改方法（函数）
            function openUpdate(data){
                // var obj = $("[name='id']").val();
                console.log(data);
                var mainIndex=layer.open({
                    type:1,
                    title:'编辑',
                    content:$("#UpdateDiv"),
                    area:['800px','600px'],
                    success:function (index){
                        form.val("dataFrom",data);
                        url="/http://localhost:8888/sys/updateEmployee";
                    },end:function(){
                        $("#UpdateDiv").css("display",'none');
                    }
                });
            }
                //模拟数据
            var data1 = [
                 {"value": "1", "title": "市场经理"}
                ,{"value": "2", "title": "市场人员"}
                ,{"value": "3", "title": "角色3"}
                ,{"value": "4", "title": "角色4"}
                ,{"value": "5", "title": "角色5"}
                ,{"value": "6", "title": "角色6"}
            ]
            //修改表单穿梭框
            transfer.render({
                 elem: '#distribution'
                ,title: ['可选角色','新增角色']
                ,data: data1
                ,id:"updateData"
                //,width: 150 //定义宽度
                ,height: 210 //定义高度
            })

            // 新增表单监听提交
            form.on('submit(doSubmit1)', function(obj){
                //序列化/提交表单
                var params = $("#dataFrm").serialize();
                var url="http://localhost:8888/sys/addEmployee";
                //打印获取到的数据
                alert(params);
                 var index = layer.msg("数据提交中，请稍后",{
                    icon:16,
                    time:false,
                    shade:0.8
                });
                $.post(url,obj.field,function (result){
                    //判断是否成功
                    if(result.code == 200){
                        //成功
                        layer.msg("操作成功",{icon:6})
                        layer.close(index);
                        layer.closeAll("iframe");
                        parent.localtion.reload();
                    }else{
                        layer.msg(result.msg,{icon:5});
                    }
                })
                    //关闭表格
                    layer.close(mainIndex);
                    //刷新表格
                    tableIns.reload();
            });
            // 新增/修改表单监听提交
            form.on('submit(doSubmit2)', function(obj){
                //序列化/提交表单
                var params = $("#dataFrom").serialize();
                var tansferData = transfer.getData("updateData")
                var roleArr = []
                tansferData.forEach(function(data){
                    roleArr.push(data.value)
                })
                obj.field["roles"] = roleArr
                alert(JSON.stringify(obj.field))
                console.log("这里是修改后的数据：", JSON.stringify(obj.field))
                var index = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
                url="http://localhost:8888/sys/updateEmployee";
                var data = $("[name='id']").val()
                $.post(url,obj.field,function (result){
                    //判断是否成功
                    if(result.code == 200){
                        //成功
                        layer.msg("操作成功",{icon:6})
                        layer.close(index);
                        layer.closeAll("iframe");
                        parent.localtion.reload();
                    }else{
                        layer.msg(result.msg,{icon:5});
                    }
                    
                    //关闭弹出层
                    layer.close(mainIndex);
    
                    //刷新表格
                    tableIns.reload();
                })
            });
    
        });
    
    </script>
    </body>
</html>